<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="变量名" prop="varName">
        <el-input
          v-model="queryParams.varName"
          placeholder="请输入变量名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dmsIms:globalvar:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dmsIms:globalvar:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dmsIms:globalvar:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dmsIms:globalvar:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="globalvarList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" width="60" />
      <el-table-column label="变量名" align="center" prop="varName" />
      <el-table-column label="变量类型" align="center" prop="varType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.varType === 1" type="warning">
            普通变量
          </el-tag>
          <el-tag v-else-if="scope.row.varType === 2">特殊变量</el-tag>
          <el-tag v-else type="success">接口返回数据</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="变量规则"
        align="center"
        prop="varRules"
        show-overflow-tooltip
      />
      <el-table-column
        label="变量值"
        align="center"
        prop="varValue"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dmsIms:globalvar:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dmsIms:globalvar:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改变量字典对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="变量名" prop="varName">
          <el-input v-model="form.varName" placeholder="请输入变量名" />
        </el-form-item>
        <el-form-item label="变量类型" prop="varType">
          <el-radio-group v-model="form.varType">
            <el-radio :label="1">普通变量</el-radio>
            <el-radio :label="2">特殊变量</el-radio>
            <el-radio :label="3">接口返回数据</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.varType === 3">
          <el-form-item label="变量规则" prop="varRules">
            <el-col :span="23">
              <el-input
                v-model="form.varRules"
                placeholder="例:匹配单个数字 \d"
              />
            </el-col>
            <el-col :span="1">
              <el-popover
                placement="top-start"
                title="匹配规则"
                trigger="hover"
                width="200"
                content="匹配规则与JavaScript中RegExp正则表达式一致"
              >
                <i class="el-icon-info" slot="reference"></i>
              </el-popover>
            </el-col>
          </el-form-item>
          <el-form-item label="接口选择">
            <el-col :span="16">
              <el-cascader
                :props="props"
                v-model="cascaderValue"
                @change="handleChange"
              >
              </el-cascader>
            </el-col>
            <el-col :span="8">
              <el-button
                style="margin-left: 10px"
                type="success"
                @click="matchTest"
                >匹配测试</el-button
              >
            </el-col>
          </el-form-item>
          <el-form-item label="接口返回值">
            <el-input
              type="textarea"
              v-model="interRelResult"
              disabled
              :autosize="{ minRows: 5, maxRows: 8 }"
            />
          </el-form-item>
        </template>
        <el-form-item label="变量值" prop="varValue">
          <el-input
            v-model="form.varValue"
            type="textarea"
            placeholder="请输入内容"
            :autosize="{ minRows: 5, maxRows: 8 }"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-preventReClick
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGlobalvar,
  getGlobalvar,
  delGlobalvar,
  addGlobalvar,
  updateGlobalvar,
} from "@/api/dmsIms/globalvar";
import { mapActions, mapState } from "vuex";
import { SimplelistInterface, getInterface } from "@/api/dmsIms/interface";

export default {
  name: "Globalvar",
  computed: {
    ...mapState({
      simpleProList: (state) => state.prolist.simpleProList,
    }),
  },
  data() {
    return {
      props: {
        lazy: true,
        lazyLoad: this.casederLazyLoad,
      },
      cascaderValue: [],
      interRelResult: "",
      matchData: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 变量字典表格数据
      globalvarList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        varName: null,
        varType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        varName: [
          { required: true, message: "变量名不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    ...mapActions(["getProList"]),
    matchTest() {
      if (this.form.varRules === null || this.form.varRules === "") {
        this.$message({
          message: "请先填写变量规则",
          type: "warning",
        });
      } else {
        let dmsRule = new RegExp(this.form.varRules);
        let res = dmsRule.exec(this.matchData);
        if (res !== null) {
          if (res.length === 1) {
            this.$confirm(res[0], "匹配结果", {
              confirmButtonText: "存入变量值",
              cancelButtonText: "取消",
              type: "success",
            })
              .then(() => {
                this.form.varValue = res[0];
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消保存",
                });
              });
          } else if (res.length === 2) {
            this.$confirm(res[1], "匹配结果", {
              confirmButtonText: "存入变量值",
              cancelButtonText: "取消",
              type: "success",
            })
              .then(() => {
                console.log(res);
                this.form.varValue = res[1];
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消保存",
                });
              });
          }
        } else {
          this.$alert("没有匹配到数据", "匹配结果", {
            confirmButtonText: "确定",
          });
        }
      }
    },
    /** 查询变量字典列表 */
    getList() {
      this.loading = true;
      listGlobalvar(this.queryParams).then((response) => {
        this.globalvarList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    casederLazyLoad(node, resolve) {
      const { level } = node;
      if (level === 0) {
        this.getFirstNode(node, resolve);
      }
      if (level === 1) {
        this.getChildrenNode(node, resolve);
      }
    },
    handleChange(value) {
      getInterface(value[1]).then((response) => {
        this.matchData = this.interRelResult = response.data.interRelResult;
        if (this.interRelResult === null || this.interRelResult === "") {
          this.interRelResult = "该接口暂无返回值！";
        } else {
          this.interRelResult = JSON.stringify(
            JSON.parse(response.data.interRelResult),
            null,
            2
          );
        }
      });
    },
    getFirstNode(node, resolve) {
      this.getProList()
        .then(() => {
          let treeData = [];
          for (let index = 0; index < this.simpleProList.length; index++) {
            treeData.push({
              value: this.simpleProList[index].id,
              label: this.simpleProList[index].proName,
              leaf: false,
            });
          }
          return treeData;
        })
        .then((res) => {
          resolve(res);
        });
    },
    getChildrenNode(node, resolve) {
      let proId = node.data.value;
      let returnData = [];
      // this.nodeTreeData = [];
      SimplelistInterface(proId)
        .then((response) => {
          response.rows.forEach((elem) => {
            returnData.push({
              value: elem.id,
              label: elem.interName,
              leaf: true,
            });
          });
          return returnData;
        })
        .then((res) => {
          resolve(res);
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        varName: null,
        varType: 1,
        varValue: null,
        varRules: null,
        varInter: null,
        varPro: null,
        status: 0,
        createTime: null,
        updateTime: null,
      };
      this.cascaderValue = [];
      this.interRelResult = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加变量字典";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getGlobalvar(id)
        .then((response) => {
          this.form = response.data;
          if (
            this.form.varPro !== null &&
            this.form.varPro !== "" &&
            this.form.varInter !== null &&
            this.form.varInter !== ""
          ) {
            this.cascaderValue.push(Number(this.form.varPro));
            this.cascaderValue.push(Number(this.form.varInter));
            this.handleChange(this.cascaderValue);
          }
        })
        .then((_) => {
          this.open = true;
          this.title = "修改变量字典";
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.varType !== 3) {
            this.form.varRules = "";
            this.cascaderValue = [];
          }
          if (this.cascaderValue.length > 0) {
            this.form.varPro = this.cascaderValue[0].toString();
            this.form.varInter = this.cascaderValue[1].toString();
          }
          if (this.form.id != null) {
            updateGlobalvar(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGlobalvar(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除变量字典编号为"' + ids + '"的数据项？')
        .then(function () {
          return delGlobalvar(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "dmsIms/globalvar/export",
        {
          ...this.queryParams,
        },
        `globalvar_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style>
.el-cascader-node__label {
  font-size: 14px;
  width: 7vw;
  overflow: hidden;
  word-break: keep-all;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.el-cascader--medium {
  width: 100%;
}
</style>
